package com.lyd.sweet.web.controller;

import com.github.pagehelper.PageInfo;
import com.lyd.sweet.model.BasicService;
import com.lyd.sweet.web.annotation.CreateValidated;
import com.lyd.sweet.web.annotation.UpdateValidated;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;

public abstract class AbstractBasicController<QUERY, DTO, VO> {

    private final BasicService<QUERY, DTO, VO> basicService;

    protected AbstractBasicController(BasicService<QUERY, DTO, VO> basicService) {
        this.basicService = basicService;
    }

    @ApiOperation("新增")
    @PostMapping
    public VO create(@Validated(value = CreateValidated.class) @RequestBody DTO dto) {
        return (VO) this.basicService.create(dto);
    }

    @ApiOperation("删除")
    @DeleteMapping("/{id}")
    public Boolean delete(@Valid @NotNull(message = "删除记录编号不可为空") @PathVariable Long id) {
        return this.basicService.delete(id);
    }

    @ApiOperation("更新")
    @PutMapping
    public Boolean update(@Validated(value = UpdateValidated.class) @RequestBody DTO dto) {
        return this.basicService.update(dto);
    }

    @ApiOperation("根据id获取")
    @GetMapping("/{id}")
    public VO getById(@Valid @NotNull(message = "删除记录编号不可为空") @PathVariable Long id) {
        return (VO) this.basicService.getById(id);
    }

    @ApiOperation("根据查询条件获取列表")
    @PostMapping("/list")
    public List<VO> list(@RequestBody QUERY query) {
        return this.basicService.list(query);
    }

    @ApiOperation("根据查询条件获取分页")
    @PostMapping("/pages")
    public PageInfo<VO> pages(@RequestBody QUERY query) {
        return this.basicService.pages(query);
    }
}
